//
//  CLViewController.m
//  CLBrowser
//
//  Created by chuck on 2021/7/8.
//

#import "CLViewController.h"
#import <YYKit/YYKit.h>
#import "CLUserDefaults.h"
#import "CLWebDataView.h"
@interface CLViewController ()

// viewModel
@property (nonatomic, readwrite, strong) CLViewModel *viewModel;

@end

@implementation CLViewController

- (void)dealloc
{
    /// 销毁时保存数据
//    [SBPhotoManager configureSelectOriginalPhoto:_isSelectOriginalPhoto];
    CLDealloc;
}
- (void)setTitle:(NSString *)title {
    [super setTitle:title];
    self.viewModel.title = title;
}
// when `CLViewController ` created and call `viewDidLoad` method , execute `bindViewModel` method
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    CLViewController *viewController = [super allocWithZone:zone];
    @weakify(viewController)
    [[viewController
      rac_signalForSelector:@selector(viewDidLoad)]
     subscribeNext:^(id x) {
         @strongify(viewController)
         [viewController bindViewModel];
     }];
    return viewController;
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self bindInitViewModel:[[CLViewModel alloc]initWithServices:CLNavigationService params:nil]];
    }
    return self;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        [self bindInitViewModel:[[CLViewModel alloc]initWithServices:CLNavigationService params:nil]];
    }
    return self;
}

- (instancetype)initWithViewModel:(CLViewModel *)viewModel {
    self = [super init];
    if (self) {
        [self bindInitViewModel:viewModel];
    }
    return self;
}

- (void)bindInitViewModel:(CLViewModel *)viewModel {
    [self reflushLayout];
    self.viewModel = [[CLViewModel alloc]initWithServices:CLNavigationService params:nil];
    self.viewModel.rootViewControllerClass = [self class];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    /// 隐藏导航栏细线
    self.viewModel.prefersNavigationBarBottomLineHidden?[(CLNavigationController *)self.navigationController hideNavigationBottomLine]:[(CLNavigationController *)self.navigationController showNavigationBottomLine];
    /// 配置键盘
    IQKeyboardManager.sharedManager.enable = self.viewModel.keyboardEnable;
    IQKeyboardManager.sharedManager.shouldResignOnTouchOutside = self.viewModel.shouldResignOnTouchOutside;
    IQKeyboardManager.sharedManager.keyboardDistanceFromTextField = self.viewModel.keyboardDistanceFromTextField;
    /// 这里做友盟统计
    //    [MobClick beginLogPageView:SBPageName(self)];
//    [CLMediator sharedInstance].currentVc = self;
}


- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.viewModel.willDisappearSignal sendNext:nil];
    
    // Being popped, take a snapshot
    if ([self isMovingFromParentViewController]) {
        self.snapshot = [self.navigationController.view snapshotViewAfterScreenUpdates:NO];
    }
    
    /// 这里做友盟统计
    //    [MobClick endLogPageView:SBPageName(self)];
    [SVProgressHUD dismiss];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    /// ignore adjust auto scroll 64
    /// CCQC: 适配 iOS 11.0 ,iOS11以后，控制器的automaticallyAdjustsScrollViewInsets已经废弃，所以默认就会是YES
    /// iOS 11新增：adjustContentInset 和 contentInsetAdjustmentBehavior 来处理滚动区域
    ///
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
    if (@available(iOS 11.0, *)) {
        self.automaticallyAdjustsScrollViewInsets = YES;
    }else{
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
#pragma clang diagnostic pop
    
    self.extendedLayoutIncludesOpaqueBars = YES;
    /// backgroundColor
    WEAK_SELF;
    if (@available(iOS 13.0, *)) {
        UIColor *backgroundColor = [UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull traitCollection) {
            return [traitCollection userInterfaceStyle] == UIUserInterfaceStyleDark ? UIColorFromRGB(0x3C3C3C) : CL_MAIN_BACKGROUNDCOLOR;
        }];
        weakSelf.view.backgroundColor = backgroundColor;
    }
    
    if ([CLUserDefaults boolForKey:CLKeyNightStatus]) {
        weakSelf.view.backgroundColor = [UIColor blackColor];
    } else {
        weakSelf.view.backgroundColor = CL_MAIN_BACKGROUNDCOLOR;
    }
    
    /// 导航栏隐藏 只能在ViewDidLoad里面加载，无法动态
    self.fd_prefersNavigationBarHidden = self.viewModel.prefersNavigationBarHidden;
    NSLog(@"导航栏隐藏 %@,%@,%@",self.className,self.viewModel,@(self.viewModel.prefersNavigationBarHidden));
    /// pop手势
    self.fd_interactivePopDisabled = self.viewModel.interactivePopDisabled;
    
    /// 先记录
//    self.isSelectOriginalPhoto = [SBPhotoManager isSelectOriginalPhoto];
    
    /// 后重置
//    [SBPhotoManager configureSelectOriginalPhoto:NO];
    
    [self initialize];
    
    [self addSubviews];
    
    [self addComplete];
    
    [self.view insertSubview:self.backgroundView atIndex:0];
    [self.view insertSubview:self.contentView aboveSubview:self.backgroundView];
    if (self.viewModel.prefersShowHalfAndAlertContainView) {
        [self.view bringSubviewToFront:self.halfContainView];
        [self.view bringSubviewToFront:self.alertContainView];
    }
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
    
    self.navigationItem.backBarButtonItem = backItem;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    [UIApplication sharedApplication].statusBarHidden = NO;
#pragma clang diagnostic pop
    [self reflushLayout];
    
    
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self becomeFirstResponder];
}

- (void)initialize {
    
}

- (void)addSubviews {
    
}

- (void)addComplete {
    
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    self.backgroundView.frame = self.view.bounds;
    self.contentView.frame = UIEdgeInsetsInsetRect(self.view.bounds, self.contentInset);
  
    [self.view insertSubview:self.backgroundView atIndex:0];
    [self.view insertSubview:self.contentView aboveSubview:self.backgroundView];
    
    if (self.viewModel.prefersShowHalfAndAlertContainView) {
        self.halfContainView.frame = self.view.bounds;
        self.alertContainView.frame = self.view.bounds;
        [self.view bringSubviewToFront:self.halfContainView];
        [self.view bringSubviewToFront:self.alertContainView];
    }
}

// bind the viewModel
- (void)bindViewModel{
    /// set navgation title
    /// CCQC Fixed: 这里只是单纯设置导航栏的title。 不然以免self.title同时设置了navigatiItem.title, 同时又设置了tabBarItem.title
    
    @weakify(self);
    
    RAC(self.navigationItem , title) = RACObserve(self, viewModel.title);
    /// 绑定错误信息
    [self.viewModel.errors subscribeNext:^(NSError *error) {
        /// 这里可以统一处理某个错误，例如用户授权失效的的操作
        NSLog(@"...错误...");
    }];
    
    /// 动态改变
    [[[RACObserve(self.viewModel, interactivePopDisabled) distinctUntilChanged] deliverOnMainThread] subscribeNext:^(NSNumber * x) {
        @strongify(self);
        self.fd_interactivePopDisabled = x.boolValue;
    }];
}

#pragma mark - Orientation
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {return UIInterfaceOrientationMaskPortrait;}
- (BOOL)shouldAutorotate {return YES;}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {return UIInterfaceOrientationPortrait;}

#pragma mark - Status bar
- (BOOL)prefersStatusBarHidden { return NO; }
- (UIStatusBarStyle)preferredStatusBarStyle {
    if (@available(iOS 13.0, *)) {
        return UIStatusBarStyleDarkContent;
    } else {
        return UIStatusBarStyleDefault;
    }
}
- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation { return UIStatusBarAnimationFade; }

- (void)setVcType:(NSInteger)vcType {
    
}

- (void)presentViewController:(UIViewController *)viewControllerToPresent animated:(BOOL)flag completion:(void (^)(void))completion {
//    [CLMediator sharedInstance].currentVc = viewControllerToPresent;
    [super presentViewController:viewControllerToPresent animated:flag completion:completion];
}

- (CLBaseView *)backgroundView {
    if (!_backgroundView) {
        _backgroundView = [[CLBaseView alloc]initWithFrame:self.view.bounds];
    }
    return _backgroundView;
}
- (CLBaseView *)contentView {
    if (!_contentView) {
        _contentView = [[CLBaseView alloc] initWithFrame:UIEdgeInsetsInsetRect(self.view.bounds, self.contentInset)];
        _contentView.layer.masksToBounds = YES;
    }
    return _contentView;
}
- (CLFloatAlertView *)halfContainView {
    if (!_halfContainView) {
        _halfContainView = [[CLFloatAlertView alloc]initWithFrame:self.view.bounds];
        [self.view addSubview:_halfContainView];
    }
    return _halfContainView;
}
- (CLFloatAlertView *)alertContainView {
    if (!_alertContainView) {
        _alertContainView = [[CLFloatAlertView alloc]initWithFrame:self.view.bounds];
        [self.view addSubview:_alertContainView];
    }
    return _alertContainView;
}

- (BOOL)isHiddenNaviBar
{
    return self.fd_prefersNavigationBarHidden;
}
- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection {
    [super traitCollectionDidChange:previousTraitCollection];
    if (@available(iOS 13.0, *)) {
        UIColor *backgroundColor = [UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull traitCollection) {
            return [traitCollection userInterfaceStyle] == UIUserInterfaceStyleDark ? UIColorFromRGB(0x3C3C3C) : CL_MAIN_BACKGROUNDCOLOR;
        }];
        self.view.backgroundColor = backgroundColor;
    }
}

- (void)reflushLayout {
    UINavigationBar *navigationBar = self.navigationController.navigationBar;
    if (navigationBar) {
        UIEdgeInsets insets = UIEdgeInsetsMake(AUTO_TOP, 0, AUTO_BOTTOM, 0);
        if (![self isHiddenNaviBar]) {
            insets.top = NAVBAR_HEIGHT;
        }
        self.contentInset = insets;
    }
}

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
    [[CLWebDataView shared] motionEnded:motion withEvent:event];
}
- (BOOL)canBecomeFirstResponder {
    return YES;
}
@end
